package com.abing.starry.common;

import com.abing.starry.exception.ThrowUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * @Author CaptainBing
 * @Date 2024/8/23 22:19
 * @Description 生成基础增删改查
 */
public interface BaseController<T> {

    IService<T> getService();

    @GetMapping("/_query")
    default BaseResponse<IPage<T>> query(QueryParamEntity queryParamEntity){
        Page<T> page = new Page<>(queryParamEntity.getCurrent(), queryParamEntity.getPageSize());
        return ResultUtils.success(getService().page(page, Wrappers.emptyWrapper()));
    }

    @GetMapping("/_query/{id}")
    default BaseResponse<T> queryById(@PathVariable String id){
        return ResultUtils.success(getService().getById(id));
    }

    @PostMapping("/_save")
    default BaseResponse<Boolean> save(@RequestBody T payload){
        return ResultUtils.success(getService().save(payload));
    }

    @PostMapping("/_batch")
    default BaseResponse<Boolean> batch(@RequestBody List<T> payload){
        return ResultUtils.success(getService().saveBatch(payload));
    }

    @DeleteMapping("/_delete/{id}")
    default BaseResponse<Boolean> delete(@PathVariable String id){
        ThrowUtils.throwIf(Objects.isNull(getService().getById(id)),ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(getService().removeById(id));
    }

    @PutMapping("/_update")
    default BaseResponse<Boolean> update(@RequestBody T payload){
        return ResultUtils.success(getService().updateById(payload));
    }

}
